<template>
  <el-container class="app_container flex">
    <Aside @handleNodeClick="handleNodeClick" />
    <el-main class="app_main flex">
      <Breadcrumb :title="pageTitle" />
      <div class="app_content">
        <el-form ref="searchForm" :model="searchMap">
          <el-row class="flex serach_item pb10">
            <span class="label-tip">设施类型：</span>
            <el-button v-for="(item, index) in this.facilityTypeList" :key="item.safeDeviceTypeId + index" type="primary" :class="setFacilityTypeActive(item.safeDeviceTypeId)" @click="getList(item)">{{ item.safeDeviceTypeName }}（{{ item.deviceNum }}）</el-button>
          </el-row>
          <div class="serach_wrapper flex-space-between el-form--inline">
            <div class="search flex">
              <el-form-item prop="deviceName" size="small">
                <el-input v-model="searchMap.deviceName" placeholder="请输入设备名称"></el-input>
              </el-form-item>
              <el-form-item prop="expireStatus" size="small">
                <el-select v-model="searchMap.expireStatus" placeholder="是否到期" clearable>
                  <el-option v-for="dict in dict.type.facility_expired" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>

              <el-form-item class="flex">
                <el-button @click="handleSearch()" class="btn_primary">查询</el-button>
                <el-button @click="handleReset()" class="btn_cancel">重置</el-button>
              </el-form-item>
            </div>
            <div class="edit">
              <el-form-item class="flex">
                <el-button @click="handleAdd" class="btn_primary" icon="el-icon-plus"> 新增 </el-button>
                <el-button @click="handleDelete" class="btn_primary" icon="el-icon-delete"> 删除 </el-button>
              </el-form-item>
            </div>
          </div>
        </el-form>

        <el-table :data="dataList" v-loading="loading" stripe class="per_table" @selection-change="handleSelectionChange" :height="winTableH" style="width: 100%;">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column align="center" label="序号" type="index"></el-table-column>
          <el-table-column prop="safeDeviceTypeName" align="center" label="设备类型"></el-table-column>
          <el-table-column prop="deviceBrandName" align="center" label="设备品牌"></el-table-column>
          <el-table-column prop="deviceCode" align="center" label="设备编码"></el-table-column>
          <el-table-column prop="deviceName" align="center" label="设备名称"></el-table-column>
          <el-table-column prop="deptName" align="center" label="所属项目"></el-table-column>
          <el-table-column prop="installPosition" align="center" label="设备位置"></el-table-column>
          <el-table-column prop="installTime" align="center" label="安装日期"></el-table-column>
          <el-table-column prop="expireTime" align="center" label="到期日期"></el-table-column>
          <el-table-column prop="remark" align="center" label="备注"></el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template slot-scope="scope">
              <div class="">
                <span type="text" class="tag_primary" size="small" @click="handleEdit(scope.row)">编辑</span>
                <!-- <span type="text" class="tag_warning" size="small" @click="handleDelete(scope.row)">删除</span> -->
                <span type="text" class="tag_primary" size="small" @click="handleDetail(scope.row)">查看</span>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <Pagination v-show="total > 0" :total="total" :page.sync="searchMap.pageNum" :limit.sync="searchMap.pageSize" @change="getList"></Pagination>
        <!-- 分页over -->

      </div>

    </el-main>


    <!-- 弹窗 新增/编辑 -->
    <FireSafetyEquipmentForm ref="addForm" :formData="formData" :facilityTypeList="facilityTypeList" :dictMap="dict" :titleIndex="titleIndex" :dialogVisible="dialogVisible" @cancel="cancel" @getList="getListFacilityTypesData"></FireSafetyEquipmentForm>
    <!-- 弹窗 新增/编辑 over -->

    <!-- 弹窗 详情 -->
    <FireSafetyEquipmentDetail :descData="descData" :dictMap="dict" :dialogVisible="dialogVisibleDetail" @cancel="cancelDetail"></FireSafetyEquipmentDetail>
    <!-- 弹窗 详情 over -->
  </el-container>
</template>

<script>
import Aside from '@/components/Aside';
import Breadcrumb from '@/components/Breadcrumb';
import FireSafetyEquipmentForm from '@/views/fireSafetyEquipment/FireSafetyEquipmentForm';
import FireSafetyEquipmentDetail from '@/views/fireSafetyEquipment/FireSafetyEquipmentDetail';
import { getDeviceBrandList } from "@/api/system/device/brand";

import { listSafeDevice, getSafeDevice, addSafeDevice, updateSafeDevice, delSafeDevice, getStatSafeDeviceNumByType } from '@/api/fireSafetyEquipment';

import { EventBus } from '@/utils/eventbus';

export default {
  name: 'facilityManagement',
  dicts: ['facility_expired'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 设施类型列表
      facilityTypeList: [],
      // 搜索条件
      searchMap: {
        deptId: '',
        deviceName: '',
        expireStatus: '',
        safeDeviceTypeId: '',
        pageNum: 1,
        pageSize: 10,
      },
      // 数据列表
      dataList: [],
      // 总条数
      total: 0,
      // 表单字段数据
      formData: {
        safeDeviceTypeId: '',
        deviceBrandId: '',
        deviceCode: '',
        deviceName: '',
        projectPointId: '',
        installPosition: '',
        installTime: '',
        expireTime: '',
        remark: '',
      },
      descData: {},
      // 弹窗-新增，编辑头文字
      titleIndex: 0,
      // 弹窗-新增/编辑-显示隐藏
      dialogVisible: false,
      // 弹窗-详情-显示隐藏
      dialogVisibleDetail: false,
      // 安消设施类型统计总数
      sum: 0,
      // 当前树节点数据
      currentTreeData: {},
      // 设备品牌列表
      deviceBrandList: [],
    };
  },
  computed: {
    pageTitle() {
      return '安消设施';
    },
  },
  watch: {},
  created() {
  },
  mounted() {
    EventBus.$on('currentTree', async data => {
      this.searchMap.deptId = data.id
      this.currentTreeData = data
      await this.toGetDeviceBrandList()
      this.getListFacilityTypesData()
    })
  },
  methods: {
    /** 查询按钮操作 */
    handleSearch() {
      this.searchMap.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    handleReset() {
      this.searchMap.deviceName = ''
      this.searchMap.expireStatus = ''

      this.formData = {
        safeDeviceTypeId: '',
        deviceBrandId: '',
        deviceCode: '',
        deviceName: '',
        projectPointId: this.currentTreeData.projectPointId,
        projectPointName: this.currentTreeData.projectPointName,
        installPosition: '',
        installTime: '',
        expireTime: '',
        remark: '',
      }
      this.getList();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.safeDeviceId);
      this.multiple = !selection.length;
    },
    // 新增设备
    handleAdd() {
      this.titleIndex = 0;
      this.dialogVisible = true;
      this.handleReset()
      this.$refs.addForm.toGetDeviceBrandList(this.deviceBrandList)
    },
    // 修改数据
    handleEdit(row) {

      // 请求编辑数据后赋值
      this.formData = JSON.parse(JSON.stringify(row));
      this.formData.projectPointName = this.currentTreeData.projectPointName
      this.$refs.addForm.toGetDeviceBrandList(this.deviceBrandList)
      this.titleIndex = 1;
      this.dialogVisible = true;
    },
    // 查看详情
    handleDetail(row) {

      // 请求设备品牌列表
      getDeviceBrandList(row.safeDeviceTypeId).then(res => {
        if (200 === res.code) {
          this.descData = row;
          let item = res.rows.filter(item => item.deviceBrandId == row.deviceBrandId)[0]
          if (item) {
            this.descData.deviceBrandName = item.deviceBrandName
          }
          this.descData.projectPointName = this.currentTreeData.projectPointName
          this.dialogVisibleDetail = true;
        }
      })
    },
    // 弹窗新增编辑-取消
    cancel() {
      this.dialogVisible = false;
    },
    // 弹窗详情-取消
    cancelDetail() {
      this.dialogVisibleDetail = false;
    },
    // 节点点击触发
    handleNodeClick(data) {
      this.searchMap.deptId = data.id;
      // this.searchMap.projectPointName = data.projectPointName
      // this.searchMap.projectPointId = data.projectPointId
      this.searchMap.pageNum = 1;

      this.currentTreeData = data

      this.getListFacilityTypesData();
    },
    // 获取安消设施类型列表
    getListFacilityTypesData() {
      // 获取安消设施类型列表下各个设备数量
      getStatSafeDeviceNumByType({ deptId: this.searchMap.deptId }).then(res => {
        if (200 === res.code) {
          this.sum = 0
          let arr = res.data.map((item, index) => {
            item.safeDeviceType.deviceNum = item.deviceNum
            this.sum += item.deviceNum
            return item.safeDeviceType
          })

          this.$refs.addForm.setFacilityTypeList(arr)

          this.facilityTypeList = [{ safeDeviceTypeName: "全部", deviceNum: this.sum, safeDeviceTypeId: '' }].concat(arr)

          this.searchMap.pageNum = 1;
          this.getList()
        }
      })
    },
    // 获取安消设施列表
    getList(data) {
      if (data) {
        this.searchMap.safeDeviceTypeId = data.safeDeviceTypeId
      }
      if (!this.searchMap.deptId) {
        this.$message({
          message: "请先选择项目点类型",
          type: "warning",
        });
        return
      }
      this.loading = true;
      listSafeDevice(this.searchMap).then(res => {
        if (200 === res.code) {
          this.dataList = res.rows.map(item => {
            // 添加安消设施类型名称
            let obj = this.facilityTypeList.filter(item2 => item2.safeDeviceTypeId == item.safeDeviceTypeId)[0]
            if (obj) {
              item.safeDeviceTypeName = obj.safeDeviceTypeName
            }

            // 添加设备品牌名称
            let deviceBrandObj = this.deviceBrandList.filter(item2 => item2.deviceBrandId == item.deviceBrandId)[0]
            if (deviceBrandObj) {
              item.deviceBrandName = deviceBrandObj.deviceBrandName
            }
            return item
          })
          this.total = res.total;
        }
        this.loading = false;
      });
    },
    // 删除数据
    handleDelete(row) {
      const ids = row.safeDeviceId ? [row.safeDeviceId] : this.ids;
      if (ids && ids.length) {
        this.$confirm('是否确认删除所选数据项？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          delSafeDevice(ids).then(res => {
            if (res && res.code == 200) {
              this.$message.success('删除成功');
              this.getListFacilityTypesData();
            }
          });
        });
      } else {
        this.$message.warning('请选择数据进行删除');
      }
    },
    // 设备系统类型设置选中项
    setFacilityTypeActive(id) {
      return id == this.searchMap.safeDeviceTypeId ? "btn_group_active" : "btn_group"
    },
    // 获取设备品牌列表
    toGetDeviceBrandList() {
      getDeviceBrandList({}).then(res => {
        if (200 == res.code) {
          this.deviceBrandList = res.rows
        }
      })
    },
  },
  components: {
    Aside,
    FireSafetyEquipmentForm,
    FireSafetyEquipmentDetail
  },
  beforeDestroy: function () {
    EventBus.$off('currentTree');
  },
}
</script>

<style lang='less' scoped>
/deep/ .btn_group.el-button {
  width: auto;
}
</style>